//
// ZyaZhangWebController.swift
//  LayerAssistance
//
//  Created by qiuxiankai on 2016/12/23.
//  Copyright © 2016年 四美达. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD

class ZyaZhangWebController: UIViewController, WKNavigationDelegate, WKUIDelegate {
    

    
    var loadUrl = ""
    var one = ZyaBillModel(JSON: ["id_key" : ""])! {
        didSet {
        
            getIfFace(clientId: one.sClientId.unwrap,finish: { (str,name,idno,phone) in
                self.ifVeifyStr = str
                self.idno = idno
            }, error: { estr in
                KSToast(estr)
            })
            
            
        }
    }
 
    
    /// 新闻id  如果不等于0  则根据id获取新闻内容
    var newsId = 0
    var  ifVeifyStr = "未认证"
    var idno = ""
    var commonWebview = WKWebView()
     
    fileprivate lazy var progress: UIProgressView = {
        let progress = UIProgressView()
        progress.frame = CGRect(x: 0, y: 0, width: self.view.ks_width, height: 5)
        progress.backgroundColor = #colorLiteral(red: 0.1803921569, green: 0.1960784314, blue: 0.568627451, alpha: 1)
        self.view.addSubview(progress)
        return progress
    }()
  
    override func viewDidLoad() {
        super.viewDidLoad()
   
   
//        if self.title == "报表" {
//            let item = UIBarButtonItem(title: "签章", style: .done, target: self, action: #selector(signAction))
//            self.navigationItem.rightBarButtonItem = item
//        }
        
        
        
     
        
        
        let config = WKWebViewConfiguration()
        config.preferences = WKPreferences()
        config.preferences.minimumFontSize = 18
        config.processPool = WKProcessPool()
        
 
        
        commonWebview = WKWebView(frame: self.view.bounds, configuration: config)
        //添加webView
        commonWebview.navigationDelegate = self
        commonWebview.uiDelegate = self
        view.addSubview(commonWebview)

        if let urlX = URL(string: self.loadUrl) {
            commonWebview.load(URLRequest(url:urlX))
        } else {
            KSToast("url有问题")
            return
        }
//
        //进度条
        commonWebview.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        
       
    }
    
    @objc func signAction() {
            if self.ifVeifyStr == "已认证" {
                if self.one.url == "0" {
                    self.heqianAction(self.idno)
                } else {
                    let alert = UIAlertController(title: "提示", message: "该对账单已签，是否重新签章", preferredStyle: .alert)
                    let delete = UIAlertAction(title: "确定", style: .default) { (_) in
                        self.heqianAction(self.idno)
                    }
                    let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                    alert.addAction(delete)
                    alert.addAction(cancel)
                    self.present(alert, animated: true, completion: nil)
                    
                }
            } else {
                let view = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "VerifyFirstController") as! VerifyFirstController
                self.navigationController?.pushViewController(view, animated: true)
            }
   
    }
    func heqianAction (_ idno:String) {
     
        KSNetwork.shared.doRequest(API.signature(userId: USERINFO.usrid!, time: self.one.sMonth!, code: self.one.orgCode!, clientId: self.one.sClientId!,idNo: idno),showHud: true) { (data: OperateResult) in
            if data.flag == TRUE {
                let webview = ZyaZhangWebController()
                webview.loadUrl =  data.url.unwrap
                webview.title = "签署"
                self.navigationController?.pushViewController(webview, animated: true)
                
                
            } else {
                KSToast("错误,\(data.message ?? "")")
            }
        }
        
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            print(commonWebview.estimatedProgress)
            progress.progress = Float(commonWebview.estimatedProgress)
        }
        
        if !commonWebview.isLoading {
            UIView.animate(withDuration: 0.55, animations: { () -> Void in
                self.progress.alpha = 0.0;
            })
        }

    }
    
    
    deinit {
        print("网页显示销毁")
        commonWebview.removeObserver(self, forKeyPath: "estimatedProgress")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}

// MARK: navigationDelegate
extension ZyaZhangWebController {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        UIView.animate(withDuration: 0.55, animations: { () -> Void in
            self.progress.alpha = 0.0;
        })
        let str = "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '80%'"
        webView.evaluateJavaScript(str) { (response, error) in
            
        }
        let str2 = "javascript:var imgs = document.getElementsByTagName('img');for(var i = 0; i<imgs.length; i++){imgs[i].style.width = '90%';imgs[i].style.height = 'auto';}"
        webView.evaluateJavaScript(str2) { (response, error) in
            
        }
        
    }
   
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("加载出了点问题")
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("start")
    }
}
